<?php

namespace app\backstage\controller;

use think\Controller;
use think\Request;
use app\backstage\model\Admin;

class BaseLogin extends Controller
{
    public  function __construct(Request $request)
    {
        parent::__construct();


        $action = $request->action();
        if($action=='login' || $action=='verify'){
            return true;
        }

        $this->check($request);

    }


    public function check($request){

        $login_token = cookie('login_token');

        $login_url = config('template.root_path').'/login';

        //未登录跳转到登录页
        if(!$login_token){

            if($request->isAjax()){
                return json(['code'=>102,'msg'=>'请重新登录']);
            }

            // return redirect(config('template.root_path').'/login');


            echo <<<DDD
            <script>window.top.location.href="$login_url"</script>
DDD;
            exit;

        }

        $row = Admin::where('login_token',$login_token)->find();

        //token失效
        if(!$row){


            if($request->isAjax()){
                return json(['code'=>102,'msg'=>'请重新登录']);
            }

            echo <<<DDD
            <script>window.top.location.href="$login_url"</script>
DDD;
            exit;
            // return redirect(config('template.root_path').'/login');
        }

        $request->role_id = $row['role_id'];
        $request->admin_id = $row['id'];
        $request->admin_name = $row['name'];

    }
}